#ifndef __COMUNICATE_H__
#define __COMUNICATE_H__

#include <Arduino.h>
#include <WiFi.h>
#include "config.h"
#include "AsyncUDP.h"

class UDPComunicate : public AsyncUDP
{
public:
    char *ssid = WIFI_SSID;
    char *pass = WIFI_PASS;
    IPAddress remote_IP;
    unsigned int localPort = 8888;
    UDPComunicate() : AsyncUDP(){};

    void begin(int port)
    {
        localPort = port;
         if (!WiFi.config(IPAddress(192, 168, 0, 100), IPAddress(192, 168, 0, 1), IPAddress(255, 255, 255, 0))) {
    Serial.println("STA Failed to configure");
  } 
        WiFi.begin(ssid, pass);
        while (WiFi.status() != WL_CONNECTED)
        {
            delay(500);
            Serial.print(".");
        }
        //fix ip
        // 
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        remote_IP.fromString(UDP_TARGET_IP);
        Serial.println(WiFi.localIP());
        AsyncUDP::connect(remote_IP, localPort);
        if (AsyncUDP::listen(localPort))
        {
            Serial.println("UDP Listening on IP: ");
            Serial.println(WiFi.localIP());
            Serial.print("Port: ");
            Serial.println(localPort);
            AsyncUDP::onPacket([](AsyncUDPPacket packet)
                               { Serial.printf("UDP Packet Type: %d, From %s:%d, To %s:%d, Length %u, Data: %s\n",
                                               packet.isBroadcast() ? 2 : packet.isMulticast() ? 1
                                                                                               : 0,
                                               packet.remoteIP().toString().c_str(), packet.remotePort(),
                                               packet.localIP().toString().c_str(), packet.localPort(),
                                               packet.length(),
                                               packet.data()); });
        }
        else
        {
            Serial.println("UDP Listen failed");
        }
    }
    void write(uint8_t *data, size_t len)
    {
        AsyncUDP::writeTo(data, len, remote_IP, localPort);
    }
    void write(String data)
    {
        AsyncUDP::writeTo((uint8_t *)data.c_str(), data.length(), remote_IP, localPort);
    }
};

extern UDPComunicate udp;
#endif